package com.yonyou.cyxdms.sysAuth.service.service.jwt;

import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.security.Md5Util;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.feign.IAuthProviderService;
import com.yonyou.cyxdms.sysAuth.service.service.impl.UserServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class JwtServiceImpl implements JwtService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private IAuthProviderService authProviderService;

    @Autowired
    private RedisClient redisClient;

    @Override
    public boolean delJwtInfo(String userId) {
        boolean flag = false;
        Object jwt = redisClient.get(userId);
        if (!StringUtils.isNullOrEmpty(jwt)) {
            delJwt(jwt.toString());
            flag = true;
        }
        Object pcjwt = redisClient.get(userId + SysAuthCommonConstants.JWT_CLIENT_DELIMITER + SysAuthCommonConstants.JWT_CLIENT_LOGINWAY_PC);
        if (!StringUtils.isNullOrEmpty(pcjwt)) {
            delJwt(pcjwt.toString());
            flag = true;
        }
        Object appjwt = redisClient.get(userId + SysAuthCommonConstants.JWT_CLIENT_DELIMITER + SysAuthCommonConstants.JWT_CLIENT_LOGINWAY_APP);
        if (!StringUtils.isNullOrEmpty(appjwt)) {
            delJwt(appjwt.toString());
            flag = true;
        }
        return flag;
    }

    @Override
    public boolean delJwtWithJwt(String jwt) {
        delJwt(jwt);
        return true;
    }

    private void delJwt(String jwt) {
        try {
            //随机数
//            Random random = new Random();
//            String nonce = String.valueOf(random.nextInt(10));
            String nonce = String.valueOf(RandomUtils.nextInt(0, 10));
            String occurtime = String.valueOf(System.currentTimeMillis());
            String data = SysAuthCommonConstants.AUTHORIZATION_CODE + nonce + occurtime;
            String sign = Md5Util.md5(data).toLowerCase();
            authProviderService.delJwtInfo(jwt, nonce, occurtime, sign);
        } catch (Exception e) {
            logger.info("JWT空！");
        }
    }
}
